const app = getApp()

Page({
  data: {
    currentStatus: '',
    orders: [],
    page: 1,
    pageSize: 10,
    hasMore: true,
    loading: false
  },

  onLoad() {
    this.checkLoginAndLoadOrders()
  },

  onPullDownRefresh() {
    this.resetAndReload()
  },

  checkLoginAndLoadOrders() {
    const token = wx.getStorageSync('access_token')
    if (!token) {
      wx.redirectTo({
        url: '/pages/login/login?redirect=' + encodeURIComponent('/pages/order-list/order-list')
      })
      return
    }
    this.loadOrders()
  },

  resetAndReload() {
    this.setData({
      orders: [],
      page: 1,
      hasMore: true
    }, () => {
      this.loadOrders()
    })
  },

  loadOrders() {
    if (!this.data.hasMore || this.data.loading) return

    this.setData({ loading: true })
    wx.showLoading({ title: '加载中...' })

    const token = wx.getStorageSync('access_token')
    let url = `${app.globalData.baseUrl}/orders/recycle-orders/?page=${this.data.page}&page_size=${this.data.pageSize}`
    
    // 添加状态筛选参数
    if (this.data.currentStatus) {
      url += `&status=${this.data.currentStatus}`
    }

    wx.request({
      url,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.statusCode === 200) {
          const newOrders = res.data.results.map(order => ({
            ...order,
            status_display: this.getStatusDisplay(order.status),
            appointment_time: order.appointment_time.replace('T', ' ').split('.')[0]
          }))

          this.setData({
            orders: this.data.page === 1 ? newOrders : [...this.data.orders, ...newOrders],
            hasMore: res.data.next !== null,
            page: this.data.hasMore ? this.data.page + 1 : this.data.page
          })
        } else if (res.statusCode === 401) {
          this.handleUnauthorized()
        }
      },
      fail: (err) => {
        console.error('加载订单失败:', err)
        wx.showToast({
          title: '加载失败',
          icon: 'none'
        })
      },
      complete: () => {
        this.setData({ loading: false })
        wx.hideLoading()
        wx.stopPullDownRefresh()
      }
    })
  },

  switchTab(e) {
    const status = e.currentTarget.dataset.status
    if (status === this.data.currentStatus) return

    this.setData({
      currentStatus: status,
      orders: [],
      page: 1,
      hasMore: true
    }, () => {
      wx.pageScrollTo({
        scrollTop: 0,
        duration: 0
      })
      this.loadOrders()
    })
  },

  handleUnauthorized() {
    const refreshToken = wx.getStorageSync('refresh_token')
    if (refreshToken) {
      this.refreshToken(refreshToken)
    } else {
      this.clearTokenAndRedirect()
    }
  },

  getStatusDisplay(status) {
    const statusMap = {
      'pending': '待处理',
      'confirmed': '已确认',
      'processing': '处理中',
      'completed': '已完成',
      'cancelled': '已取消'
    }
    return statusMap[status] || status
  },

  loadMore() {
    if (!this.data.loading && this.data.hasMore) {
      this.loadOrders()
    }
  },

  goToDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/order-detail/order-detail?id=${id}`
    })
  },

  cancelOrder(e) {
    const id = e.currentTarget.dataset.id
    
    wx.showModal({
      title: '提示',
      content: '确定要取消这个订单吗？',
      success: (res) => {
        if (res.confirm) {
          const token = wx.getStorageSync('access_token')
          wx.request({
            url: `${app.globalData.baseUrl}/orders/recycle-orders/${id}/cancel/`,
            method: 'POST',
            header: {
              'Authorization': `Bearer ${token}`
            },
            success: (res) => {
              if (res.statusCode === 200) {
                wx.showToast({
                  title: '订单已取消',
                  icon: 'success'
                })
                this.setData({
                  orders: [],
                  page: 1,
                  hasMore: true
                }, () => {
                  this.loadOrders()
                })
              }
            }
          })
        }
      }
    })
  }
})